//
//  MysqlDB.m
//  HiQServer
//
//  Created by scarlettsun  on 12-7-18.
//  Copyright (c) 2012年 tencent. All rights reserved.
//

#import "MysqlDB.h"

@implementation MysqlDB


-(id)init
{
    return self;
}

-(void)connectHost:(NSString *)host connectUser:(NSString *)user connectPassword:(NSString *)password connectName:(NSString *)name
{
    myconnect = mysql_init(myconnect);
    if( !mysql_real_connect(myconnect,[host UTF8String],[user UTF8String],[password UTF8String],[name UTF8String],MYSQL_PORT,NULL,0))
    {
        NSLog(@"ERROR");
        mysql_close(myconnect);
        
    }
     NSLog(@"connect success");
}

-(void)disconnect
{
    mysql_close(myconnect);
    NSLog(@"Close From Mysql");
}

-(int)query:(NSString *)sql
{
    if (myconnect == nil) {
        [self connectHost:hostIp connectUser:userName connectPassword:password connectName:dbName];
    }
    int qResult = mysql_query(myconnect, [sql UTF8String]);
    if (qResult != 0) 
    {
        NSLog(@"%@", [NSString stringWithUTF8String:mysql_error(myconnect)]); 
    } 
   return qResult;
}

-(int)realQuery:(NSString *)sql 
{
    if (myconnect == nil) {
        [self connectHost:hostIp connectUser:userName connectPassword:password connectName:dbName];
    }
    NSUInteger len = [sql lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
    if (sql == nil) {
        return -1;
    }
    int qResult = mysql_real_query(myconnect, [sql UTF8String],len);
    if (qResult != 0) 
    {
        NSLog(@"%@", [NSString stringWithUTF8String:mysql_error(myconnect)]); 
    } 
    return qResult;
}

-(MYSQL_RES *)storeResult
{
    return mysql_store_result(myconnect);
}

-(NSMutableArray *)fetchRow:(MYSQL_RES *)result
{
    MYSQL_ROW row;
    int fieldCount = mysql_field_count(myconnect);
    NSMutableArray *rowArray = nil;
    if (result == nil) {
        return nil;
    }
    if((row = mysql_fetch_row(result)))
    {
        rowArray = [[NSMutableArray alloc] init];
        for(int i = 0; i < fieldCount; i++)
        {
            if (row[i] != nil) 
            {
              [rowArray addObject:[NSString stringWithUTF8String:row[i]]];
            }
            else 
            {
                [rowArray addObject:[NSString stringWithFormat:@""]];
            }
        }
    }
    row = NULL;
    return rowArray;
}

-(NSMutableArray *)fetchAllRows:(MYSQL_RES *)result
{
    NSMutableArray *resultArray = nil;
    if (result == nil) {
        return nil;
    }
    NSUInteger rowCount = mysql_num_rows(result);
    if (rowCount <= 0) {
        return resultArray;
    }
    resultArray = [[NSMutableArray alloc] init];
    for(int i = 0; i < rowCount; i++)
    {
        [resultArray addObject:[self fetchRow:result]];
    }
    [self releaseResult:result];
    return resultArray;
}

- (void) releaseResult:(MYSQL_RES *) result
{
    mysql_free_result(result);
}

/**insert data **/
- (NSUInteger) doDataInsert:(NSString * )sql
{
    if (sql == nil || [sql isEqualToString:@""]) {
        return -1;
    }
    [self query:sql];
    NSUInteger result = mysql_insert_id(myconnect);
    return result;
}

/**update data **/
- (int) doDataUpdate:(NSString * )sql
{
    if (sql == nil || [sql isEqualToString:@""]) {
        return -1;
    }
    int result = [self query:sql];
    return result;
}
/**delete data **/
- (int) doDataDelete:(NSString * )sql 
{
    if (sql == nil || [sql isEqualToString:@""]) {
        return -1;
    }
    int result = [self query:sql];
    return result;
}
/**query data **/
- (NSMutableArray *) doDataQuery:(NSString * )sql 
{
    if (sql == nil || [sql isEqualToString:@""]) {
        return nil;
    }
    [self query:sql];
    NSMutableArray *result = [self fetchAllRows:[self storeResult]];
    return result;
}

- (NSString *) doEscapeString:(NSString *)str
{
    const char *fromChar = [str cStringUsingEncoding:NSUTF8StringEncoding];
    int length = strlen(fromChar);
    char *toChar = malloc(2*length +1);
    unsigned long result =  mysql_real_escape_string(myconnect,toChar,fromChar,length);
    if (result != 0) {
        NSString *ret = [[NSString alloc] initWithCString:toChar encoding:NSUTF8StringEncoding];
        return ret;
    }
    
    return nil;
}
@end

